﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Web;

using System.Text;

using System.Configuration;

using DataMongo;
using DataMongo.Entities;
using Quartz;


namespace BreakingHubAdmin.Services
{
    public class GetFeedsImageService : IJob
    {

        //Collects individual message and prepares a single message for email sending

        public void Execute(JobExecutionContext context)
        {
            GetFeedImage();
        }


        public static void GetFeedImage()
        {
            var connection = new RepositoryBaseMongo("FeedPost");
            var data = connection.GetAll<FeedPost>();
            foreach (var feed in data.OrderByDescending(x=>x.FeedPostId))
            {
                var imageUrl = UtilityService.GetImageUrlFromSite(feed.SourceLink);
                if (imageUrl != null)
                {
                    var path = AppDomain.CurrentDomain.BaseDirectory + "Content\\FeedImages\\";

                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);
                    var imagepath = AppDomain.CurrentDomain.BaseDirectory + "Content\\FeedImages\\" + UtilityService.RemoveSpecialCharacters(feed.Title) + ".jpg";
                    bool result = UtilityService.DownloadImageFromUrl(imageUrl, imagepath);
                    if (result == true)
                    {

                        feed.ImageURL1 = UtilityService.RemoveSpecialCharacters(feed.Title) + ".jpg";
                    }
                    else
                    {
                        feed.ImageURL1 = null;
                    }
                }
                else
                {
                    feed.ImageURL1 = null;
                }
                connection.InsertOrUpdate(feed);
            }
        }




    }
}